<template>
  <div>
    <!-- 用户信息展示 -->
    <el-descriptions title="商品信息" class="demo-border">
      <el-descriptions-item label="商品名称">{{ productName }}</el-descriptions-item>
      <el-descriptions-item label="商品规格">{{ productSpec }}</el-descriptions-item>
      <el-descriptions-item label="可用库存">{{ availableStock }} 份</el-descriptions-item>
    </el-descriptions>

    <!-- 数据表格 -->
    <el-table :data="detailList" style="width: 100%" class="goods-table">
      <el-table-column prop="stores" label="门店" width="150"></el-table-column>
      <el-table-column prop="demand" label="需求量" width="100"></el-table-column>
      <el-table-column prop="auditNum" label="审核数量" width="100">
        <template #default="{ row }">
          <!-- 根据状态显示不同数据 -->
          <span v-if="props.status === 2">{{ row.auditNum }}</span>
          <el-input v-else v-model.number="row.auditNum" @change="handleAuditChange(row)" />
        </template>
      </el-table-column>
      <el-table-column prop="storesNote" label="备注" width="200">
        <template #default="{ row }">
          <el-input v-model="row.storesNote" @change="handleAuditChange(row)" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 机身和数量统计 -->
    <div style="margin-top: 10px;">
      <el-row>
        <el-col :span="8">机身：{{ totalBody || 0 }}</el-col>
        <el-col :span="8">数量：{{ totalQuantity || 0 }}</el-col>
        <el-col :span="8">合计审核数量：{{ totalAuditNum }}</el-col>
      </el-row>
    </div>

    <el-button type="primary" @click="saveChanges" style="margin-top: 10px;">保存</el-button>
  </div>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { allocatestores } from '@/api/allocate/allocate.js';

const props = defineProps({
  id: { type: [String, Number], required: true },
  status: { type: [String, Number], required: true }
});

const detailList = ref([]);
const productName = ref(''); // 商品名称
const productSpec = ref(''); // 商品规格
const availableStock = ref(0); // 可用库存
const totalBody = ref(0); // 机身总数
const totalQuantity = ref(0); // 数量总数
const emits = defineEmits(['update:detail']);

// 动态计算合计审核数量
const totalAuditNum = computed(() => {
  if (props.status === 2) {
    // 已审核状态：直接使用后端返回的 auditNum 总和
    return detailList.value.reduce((sum, row) => sum + (row.auditNum || 0), 0);
  } else {
    // 未审核状态：使用用户输入的 auditNum 总和
    return detailList.value.reduce((sum, row) => sum + (row.auditNum || 0), 0);
  }
});

// 监听id变化，自动加载数据
watch(() => props.id, (newId) => {
  if (newId) fetchDetail();
}, { immediate: true });

// 获取详情数据
async function fetchDetail() {
  try {
    const res = await allocatestores(props.id); // GET /restocking/queryStore/{id}
    if (res.code === 200) {
      detailList.value = res.data.map(item => ({
        ...item,
        auditNum: props.status === 2 ? item.auditNum : '', // 已审核不可改
        storesNote: item.storesNote || '',
        isChanged: false
      }));
    } else {
      ElMessage.error(res.msg || '获取详情失败');
    }
  } catch (e) {
    ElMessage.error('请求出错');
  }
}

// 处理审核数量或备注变化
function handleAuditChange(row) {
  row.isChanged = true;
  // 更新机身和数量（可根据需求调整逻辑）
  totalBody.value = detailList.value.length; // 假设机身数等于门店数
  totalQuantity.value = detailList.value.reduce((sum, row) => sum + (row.demand || 0), 0);
}

// 保存更改
async function saveChanges() {
  const changedRows = detailList.value.filter(row => row.isChanged);
  if (changedRows.length === 0) {
    ElMessage.warning('没有需要保存的更改');
    return;
  }

  try {
    const res = await allocatestoresSave({
      id: props.id,
      details: changedRows.map(row => ({
        id: row.id,              // 门店id
        auditNum: row.auditNum,  // 审核数量
        storesNote: row.storesNote
      }))
    });
    if (res.code === 200) {
      ElMessage.success('保存成功');
      emits('update:detail', { 
        id: props.id, 
        auditStatus: 2, 
        auditTotal: totalAuditNum.value 
      });
    } else {
      ElMessage.error(res.msg || '保存失败');
    }
  } catch (e) {
    ElMessage.error('请求出错');
  }
}
</script>

<style scoped>
.demo-border .text {
  width: 15%;
}
.demo-border .line {
  width: 70%;
}
.demo-border .line div {
  width: 100%;
  height: 0;
  border-top: 1px solid var(--el-border-color);
}
.demo-border .line .dashed {
  border-top: 2px dashed var(--el-border-color);
}
</style>